package com.itheima.filter; /**
 * @author tongchen
 * @create 2022-12-01 20:12
 */

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //强转
        HttpServletRequest req=(HttpServletRequest) request;
        //判断是否是与登录注册相关的资源
        String[]urls={"login.jsp","register.jsp","/css/","/imgs/","loginServlet","registerServlet"};
        String url = req.getRequestURL().toString();
        for (String string:urls) {
            if(url.contains(string)){
                chain.doFilter(request,response);
                return;
            }
        }
        //检查是否登录决定是否放行

        //检查登录
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        //根据user判断是否放行
        if(user!=null){
            chain.doFilter(request, response);

        }
        else {
            //警告错误信息并进行跳转
            req.setAttribute("login_msg","您尚未登录，请先登录");
            req.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}
